#include "qpitchdetector.h"

QPitchDetector::QPitchDetector(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
}

QPitchDetector::QPitchDetector(FMOD::System * sys){

	ui.setupUi(this);
	system=sys;
	sound=0;
    channel=0;
	//pthread=NULL;
    result = system->getVersion(&version);
    AudioUtils::ERRCHECK(result);

    result = system->getNumDrivers(&numdrivers);
    AudioUtils::ERRCHECK(result);

    for (count=0; count < numdrivers; count++)
    {
        char name[256];

        result = system->getDriverInfo(count, name, 256, 0);
        AudioUtils::ERRCHECK(result);

		QString s = QString(name);
		ui.playBackDrivers->addItem(s);
    }

    result = system->getRecordNumDrivers(&numdrivers);
    AudioUtils::ERRCHECK(result);

   
    for (count=0; count < numdrivers; count++)
    {
        char name[256];

        result = system->getRecordDriverInfo(count, name, 256, 0);
        AudioUtils::ERRCHECK(result);

        QString s = QString(name);
		ui.recordDrivers->addItem(s);
    }

    memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO));

    exinfo.cbsize           = sizeof(FMOD_CREATESOUNDEXINFO);
    exinfo.numchannels      = 1;
    exinfo.format           = FMOD_SOUND_FORMAT_PCM16;
    exinfo.defaultfrequency = OUTPUTRATE;
    exinfo.length           = exinfo.defaultfrequency * sizeof(short) * exinfo.numchannels * 5;
    
    result = system->createSound(0, FMOD_2D | FMOD_SOFTWARE | FMOD_LOOP_NORMAL | FMOD_OPENUSER, &exinfo, &sound);
    AudioUtils::ERRCHECK(result);
}

QPitchDetector::~QPitchDetector()
{

}

void QPitchDetector::startDetection(){
	if(pdec!=NULL)
		pdec->terminate();
	pdec=new PitchThread(ui.noteLabel,ui.playBackDrivers,ui.recordDrivers,system,sound,channel,exinfo,key,driver,recorddriver,numdrivers,count,bin,version);
	pdec->run();
}
void QPitchDetector::stopDetection(){
	if(pdec!=NULL)
		pdec->terminate();
}
